package com.veo.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //0强制转换
        HttpServletRequest request=(HttpServletRequest) req;
        //获取请求路径
        String uri = request.getRequestURI();
        //判断是否有与登录相关的资源，排除css,js和验证码图片
        if(uri.contains("login.jsp") || uri.contains("loginServlet") || uri.contains("/css/") || uri.contains("/js/") || uri.contains("/fonts/") || uri.contains("checkCodeServlet")){
            chain.doFilter(req, resp);
        }
        else {//不包含需要验证身份，获取session的信息
            Object user = request.getSession().getAttribute("user");
            if(user!=null){
                chain.doFilter(req, resp);//有信息直接放行
            }else {
                //没有跳转登录界面，存入未登录信息
                String language = request.getParameter("language");
                request.setAttribute("language",language);
                request.setAttribute("login_megs","你尚未登录，请登录");
                request.getRequestDispatcher("/login.jsp").forward(request,resp);
            }
        }

    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
